import { createStore } from 'vuex'
import { postList, columnList } from '@/static/test/testData'
import userStore from './modules/user'
import jobs from './modules/jobs'
import { ElMessageBox } from 'element-plus'
import axios, { AxiosRequestConfig } from 'axios'

const store = createStore<StoreProp>({
  state: {
    user: {
      isLogined: false
    },
    colunms: columnList,
    posts: postList
  },
  modules: {
    userStore,
    jobs
  },
  getters: {
    columnsLen (state) {
      return state.colunms.length
    }
  },

  /**
   * 这里只能用同步的方法
   */
  mutations: {
    login (state, userParam) {
      state.user = { ...userParam }
      axios.defaults.headers.common.Authorization = `Bearer ${state.user.token}`
    },
    setColumns (state, columns) {
      state.colunms = columns
    }
  },

  /**
   * 这里同步异步的方法都可使用
   */
  actions: {
    async fetchColumns () {
      try {
        const res = await axios.get('/columns')
        // eslint-disable-next-line
        const list = res.data.list as Array<any>
        const columns: Array<ColunmProp> = []

        list.forEach(
          item => {
            const column: ColunmProp = {
              id: item._id,
              avatar: item.avatar.url,
              content: item.description,
              title: item.title
            }
            columns.push(column)
          }
        )
        this.commit('setColumns', columns)
      } catch (error) {
        ElMessageBox.alert('获取文章列表失败')
      }
    },
    async fetchColumn (context, cid) {
      console.log('cid: ', cid)

      // const res = await quickRequest(`/columns/${cid}`)
      // const columnRes = res.data
      const config: AxiosRequestConfig = {
        params: {
          __nocover: false
        }
      }
      const res = await axios.get(`/columns/${cid}`, config)
      const columnRes = res.data

      const column: ColunmProp = {
        id: columnRes._id,
        avatar: columnRes.avatar.url,
        content: columnRes.description,
        title: columnRes.title
      }
      return column
    },
    async loginAll (context, reqData) {
      const loginRes = await axios.post('/user/login', reqData)
      console.log('loginRes', loginRes)
      this.commit('login', { token: loginRes.data.token })
      // 获取当前登陆用户信息
      const currentUserRes = await axios.get('/user/current')
      const { _id, nickName } = currentUserRes.data
      const user: UserProp = {
        isLogined: true,
        id: _id,
        name: nickName
      }
      store.commit('login', user)
      return currentUserRes.data
    }
  }
})

export default store
